package gui.newComponent;

import javax.swing.*;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import java.io.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;

public class FWTextField extends JTextField{

    ArrayList<String[]> autoreq = new ArrayList<String[]>();
    boolean bool;

    public FWTextField(String value) throws IOException, UnsupportedEncodingException {
        InputStreamReader user = new InputStreamReader(new FileInputStream(value),("cp1251"));

        boolean k = false;
        String tmp = "";
        String tmp2 = "";

        if (user != null){
            for (;user.ready() == true;){
                char c = (char) user.read();
                if (Integer.valueOf(c) != KeyEvent.VK_ENTER){
                    if (String.valueOf(c).equals(";") == true ){

                        if (k){k = false;}else{k = true;}

                        if (tmp != ""){
                            if (tmp2 != ""){
                                autoreq.add(new String[]{tmp,tmp2});
                                tmp = "";
                                tmp2 = "";
                            }
                        }

                    }else{
                        if (k){tmp = tmp + c;}
                        else{tmp2 = tmp2 + c;}
                    }
                }}
        }
    }

    protected Document createDefaultModel() {
        return new AutoReq();
    }

    class AutoReq extends PlainDocument{

        public void insertString(int offs,String str,AttributeSet a) throws BadLocationException {
            String curText = getText(0, getLength());
            String bOffs = curText.substring(0, offs);
            String aOffs = curText.substring(offs, curText.length());
            String res = bOffs+str+aOffs;
            //System.out.println(str);
            bool = false;
            int ind=0;
            String s1,s2;
            for (int i=0; i<autoreq.size(); i++){
                s1 = str;
                s2 = autoreq.get(i)[0];
                if (s1.equals(s2)){
                    bool = true;
                    ind = i;
                }
            }
            if (bool){
                str = autoreq.get(ind)[1];
            };
            super.insertString(offs, str, a);
        }

    }

}
